package com.example.drools.service;

import com.example.drools.model.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 风控服务类
 */
@Service
public class RiskControlService {

    @Autowired
    private KieContainer kieContainer;

    /**
     * 执行风控评估
     */
    public List<RiskAssessment> assessRisk(UserProfile userProfile, Context context, List<Score> scores) {
        System.out.println("开始风控评估 - 用户ID: " + userProfile.getId());
        KieSession kieSession = kieContainer.newKieSession();
        List<RiskAssessment> riskAssessments = new ArrayList<>();

        try {
            // 设置焦点到风控规则组
            kieSession.getAgenda().getAgendaGroup("risk-control").setFocus();
            System.out.println("设置agenda-group焦点到: risk-control");

            // 插入事实
            kieSession.insert(userProfile);
            kieSession.insert(context);
            System.out.println("插入UserProfile和Context");
            
            // 插入所有分数
            for (Score score : scores) {
                kieSession.insert(score);
                System.out.println("插入Score: " + score.getName() + " = " + score.getValue());
            }

            // 触发规则
            int firedRules = kieSession.fireAllRules();
            System.out.println("触发了 " + firedRules + " 条规则");

            // 收集风控评估结果
            kieSession.getObjects(object -> object instanceof RiskAssessment)
                    .forEach(obj -> {
                        RiskAssessment assessment = (RiskAssessment) obj;
                        riskAssessments.add(assessment);
                        System.out.println("收集到风险评估结果: " + assessment.getRiskLevel() + " - " + assessment.getReason());
                    });

            System.out.println("最终返回 " + riskAssessments.size() + " 个风险评估结果");

        } finally {
            kieSession.dispose();
        }

        return riskAssessments;
    }

    /**
     * 简化的风控评估方法
     */
    public RiskAssessment quickAssess(String userId, String userType, double riskScore, String location) {
        UserProfile userProfile = new UserProfile();
        userProfile.setId(userId);
        userProfile.setSegments(Set.of(userType));
        userProfile.setRegion(location);

        Context context = new Context();
        context.setPage("风控检查");

        List<Score> scores = List.of(
                new Score(userId, "riskScore", riskScore),
                new Score(userId, "transactionAmount", 1000.0),
                new Score(userId, "daysSinceRegistration", 30)
        );

        List<RiskAssessment> assessments = assessRisk(userProfile, context, scores);
        
        // 返回最高优先级的风控结果
        return assessments.stream()
                .filter(assessment -> !"LOW".equals(assessment.getRiskLevel()))
                .findFirst()
                .orElse(assessments.isEmpty() ? 
                    new RiskAssessment(userId, "LOW", "NORMAL", "正常用户", true, "通过") : 
                    assessments.get(0));
    }

    /**
     * 批量风控评估
     */
    public List<RiskAssessment> batchAssess(List<UserProfile> userProfiles, Context context) {
        List<RiskAssessment> allAssessments = new ArrayList<>();
        
        for (UserProfile userProfile : userProfiles) {
            // 为每个用户生成模拟分数
            List<Score> scores = generateMockScores(userProfile.getId());
            List<RiskAssessment> userAssessments = assessRisk(userProfile, context, scores);
            allAssessments.addAll(userAssessments);
        }
        
        return allAssessments;
    }

    /**
     * 生成模拟分数数据
     */
    private List<Score> generateMockScores(String userId) {
        return List.of(
                new Score(userId, "riskScore", Math.random() * 100),
                new Score(userId, "transactionAmount", Math.random() * 10000),
                new Score(userId, "daysSinceRegistration", (int)(Math.random() * 365)),
                new Score(userId, "loginFrequency", Math.random() * 30)
        );
    }
}